import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/epidemic_item.dart';
import 'package:flutter_syt/domain/widgets/list_item.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

class EpiInfoEntity {
  String status;
  List<ListItemEntity> listData;
  EpiInfoEntity(this.status, this.listData);
}

@RoutePage(name: "epidemicPage")
class EpidemicPage extends StatefulWidget {
  @override
  _EpidemicPageState createState() => _EpidemicPageState();
}

class _EpidemicPageState extends State<EpidemicPage>
    with TickerProviderStateMixin {
  late AnimationController _colorAnimationController;
  late Animation _colorTween;
  var data;
  @override
  void initState() {
    _getEpiInfo();
    _colorAnimationController =
        AnimationController(vsync: this, duration: Duration(seconds: 0));
    _colorTween = ColorTween(begin: Colors.transparent, end: Colors.white)
        .animate(_colorAnimationController);

    super.initState();
  }

  bool _scrollListener(ScrollNotification scrollInfo) {
    if (scrollInfo.metrics.axis == Axis.vertical &&
        scrollInfo.metrics.pixels < 100) {
      _colorAnimationController.animateTo(scrollInfo.metrics.pixels / 40);
      return true;
    }
    return false;
  }

  Future _getEpiInfo() async {
    Map result = await API.shared.epidemic.reportStatus();
    bool isNewReport = result['hasNew'];
    // await API.shared.epidemic.isNewReport();
    bool isReport = result['reported'];
    // await API.shared.epidemic.isReport();
    List<EpidemicRecordItem> reportRecord =
        await API.shared.epidemic.reportRecord();
    print(reportRecord);
    List<ListItemEntity> reportData = reportRecord.map((e) {
      if (e.status == '0') {
        return ListItemEntity(
          "${e.date}",
          'assets/images/sign_fail.png',
          S.of(context).resubmit,
          () => {
            RouteManager.push(
              context,
              RoutMapping.epidemicForm(add: e.date),
            )
          },
          // leftTextStyle: const TextStyle(
          //   color: ThemeColor.colorBlack40,
          //   fontSize: 16,
          //   fontWeight: FontWeight.w400,
          // ),
          iconRight: 'assets/icons/icon_right_black.png',
          isShowBorder: false,
        );
      } else {
        return ListItemEntity(
          "${e.date}",
          'assets/images/sign_suc.png',
          S.of(context).view_details,
          () => {
            RouteManager.push(
              context,
              RoutMapping.epidemicForm(id: e.id),
            )
          },
          iconRight: 'assets/icons/icon_right_black.png',
          isShowBorder: false,
        );
      }
    }).toList();
    if (isNewReport) {
      data = EpiInfoEntity('warning', reportData);
      setState(() {
        data = data;
      });
      return;
    }
    if (isReport) {
      data = EpiInfoEntity('suc', reportData);
      setState(() {
        data = data;
      });
    } else {
      data = EpiInfoEntity('fail', reportData);
      setState(() {
        data = data;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          color: Color(0xFFF7F7F7),
        ),
        child: Stack(
          children: [
            Container(
              width: double.infinity,
              child: Image.asset(
                'assets/images/epi_banner.png',
              ),
            ),
            Container(
                height: 64 + ScreenUtil().statusBarHeight,
                child: AnimatedBuilder(
                  animation: _colorAnimationController,
                  builder: (context, child) {
                    return AppBar(
                        backgroundColor: _colorTween.value,
                        elevation: 0,
                        titleSpacing: 0.0,
                        title: Text(
                          '',
                        ));
                  },
                )),
            // Positioned(
            //   top: 45,
            //   left: 16,
            //   child: Container(
            //     width: 36,
            //     height: 36,
            //     alignment: Alignment.center,
            //     decoration: BoxDecoration(
            //       color: ThemeColor.colorBlack30,
            //       shape: BoxShape.circle,
            //     ),
            //     child: IconButton(
            //       icon: Icon(
            //         Icons.arrow_back_ios_new,
            //         color: Colors.white,
            //         size: 16,
            //       ),
            //       onPressed: () {
            //         Navigator.of(context).pop();
            //       },
            //     ),
            //   ),
            // ),
            data == null
                ? Text('')
                : Positioned.fill(
                    top: 64 + ScreenUtil().statusBarHeight,
                    left: 10,
                    right: 10,
                    child: NotificationListener<ScrollNotification>(
                      onNotification: _scrollListener,
                      child: Container(
                        width: MediaQuery.of(context).size.width,
                        child: ListView(
                          physics: BouncingScrollPhysics(),
                          children: [
                            _statusBox(data.status),
                            _signList(data.listData),
                          ],
                        ),
                      ),
                    )),
          ],
        ),
      ),
    );
  }

  Widget _statusBox(String status) {
    Map epiStatus = {
      'suc': {
        'text': S.of(context).Health_done,
        'icon': 'assets/images/epi_suc.png',
        'btnText': '',
        'click': () {}
      },
      'warning': {
        'text': S.of(context).new_report,
        'icon': 'assets/images/epi_warning.png',
        'btnText': S.of(context).viewmore,
        'click': () {
          RouteManager.push(
            context,
            RoutMapping.epidemicForm(),
          );
        }
      },
      'fail': {
        'text': S.of(context).No_todays_info,
        'icon': 'assets/images/epi_unfinish.png',
        'btnText': S.of(context).submit_now,
        'isShowBtn': true,
        'click': () {
          RouteManager.push(
            context,
            RoutMapping.epidemicForm(),
          );
        }
      },
    };
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.fromLTRB(0, 30, 0, 30),
      decoration: BoxDecoration(
        color: ThemeColor.bkColorFFFFFF,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          Container(
            width: 100,
            child: Image.asset(epiStatus[status]['icon']),
          ),
          Padding(
            padding: EdgeInsets.only(top: 10, bottom: 20),
            child: Text(
              epiStatus[status]['text'],
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: ThemeColor.colorBlack100,
              ),
            ),
          ),
          epiStatus[status]['btnText'] != ''
              ? Padding(
                  padding: EdgeInsets.only(left: 80, right: 80),
                  child: ElevatedButton(
                      child: Text(
                        epiStatus[status]['btnText'],
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: ThemeColor.colorBlack100,
                        ),
                      ),
                      onPressed: ClickUtils.debounce(
                        () async {
                          epiStatus[status]['click']();
                        },
                      )),
                )
              : Text(''),
        ],
      ),
    );
  }

  Widget _signList(List<ListItemEntity> data) {
    if (data.isEmpty) {
      return Text('');
    }
    return Container(
      margin: EdgeInsets.only(top: 10),
      decoration: BoxDecoration(
        color: ThemeColor.bkColorFFFFFF,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(15, 20, 15, 20),
            child: Text(
              S.of(context).records_14,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: ThemeColor.colorBlack100,
              ),
            ),
          ),
          Column(
            children: data
                .map((e) => GestureDetector(
                      onTap: ClickUtils.debounce(() => e.onTap),
                      child: Container(
                          // color: Colors.blueGrey,
                          alignment: Alignment.center,
                          child: ListItem(e)),
                    ))
                .toList(),
          ),
        ],
      ),
    );
  }
}
